package com.yfbao.horizon.user.injection.metrics;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Timer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
//@ConditionalOnProperty(value = "sql.enableShard", havingValue = "true")
@Component
public class ShardingMetricsAspect {

    private final MeterRegistry meterRegistry;

    @Autowired
    public ShardingMetricsAspect(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    @Around("execution(* com.yfbao..mapper..*(..))") // 修改为你的 Repository 包路径
    public Object monitorShardingQueries(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();  // 获取方法名称
        String className = joinPoint.getTarget().getClass().getSimpleName();  // 获取类名称
        String sql = joinPoint.getSignature().toShortString(); // 获取 SQL 查询
        Timer timer = Timer.builder("sharding.query.execution.time")
                .description("分片查询执行时间")
                .tag("sql", sql) // 使用 SQL 作为标签
                .register(meterRegistry);
        long start = System.currentTimeMillis();
        try {
            Object proceed = joinPoint.proceed();
            meterRegistry.counter("mybatis.sql.execution.success", "method", methodName, "class", className)
                    .increment();
            return proceed;
        }catch (Throwable t){
            meterRegistry.counter("mybatis.sql.execution.errors", "method", methodName, "class", className)
                    .increment();
            throw t;
        }finally {
            timer.record(System.currentTimeMillis()-start, TimeUnit.MILLISECONDS);
        }
    }
}
